const AUTH = require('utils/auth')
const app = getApp();
import { BASE_LOGIN_API } from "./utils/config";

import {
  getCustBaseByUserLoginState
} from "./api/custBaseController";
import { mpId } from "./utils/config";
/**
 * 全局分享
 */
// ! function () {
//   var PageTmp = Page;
//   Page = function (pageConfig) {
//     // 设置全局默认分享
//     pageConfig = Object.assign({
//       onShareAppMessage: function () {
//         return {
//           desc: '云上漂',
//           title: '云上漂',
//           path: '/pages/registration/index?bbId='+wx.getStorageSync('custId'),
//           imageUrl: '/static/images/banner.png',
//         };
//       }
//     }, pageConfig);
//     PageTmp(pageConfig);
//   };
// }();

App({
  globalData: {
    isConnected: true, //有无网络
    launchOption: undefined,
    vipLevel: 0,
    // 全局定义导航高度
    CustomBar: '',
    StatusBar: '',
    windowHeight: '',

    plumSession:'',
  },

  onLaunch: function () {
    this.checkUpdateVersion()
    this.getMenuButtonBoundingClientRect()

    this.getNetworkType()
    this.onNetworkStatusChange()

    this.share()

    this.wechatSq()
  },
  /**
   * 微信服务器登陆，以获取openid
   */
  wechatSq: function (obj) {
    var that = this;
    //调用api
    wx.login({
      success: function (res) {
        console.log("===登录微信服务器成功wx.login===,将获得code以换openid");
        var code = res.code; 
        if (res.code) {
          var data = {
            mpId: mpId, 
            code: code,
          }
          //传递code到服务器端
          wx.request({ //get方式传递数据，将接口地址与要传递的数据写在data中
            url: BASE_LOGIN_API+'/miniProgramController/onLogin',
            data: data,
            header: {
              'content-type': 'application/json' // 默认值
            },
            success: function (res) {
              if (res.data) { //调用接口成功
                console.log("向微信服务器获取用户openid成功,并以sessionid为keyd存于redis里");
                console.log(res.data)
                //sessionid存入缓存本地备用
                wx.setStorage({
                  key: "userLoginState",
                  data: res.data.data,
                  success: function () {
                    console.log('成功')
                    that.globalData.plumSession = res.data.data;
                  }
                })
                //由于这里是网络请求，可能会在 Page.onLoad 之后才返回，
                //若是idnex.js检测不到that.globalData.plumSession ，
                //会再次调用wx.login接口，浪费资源
                //所以先检测回调函数是否被创建，若未被创建代表index.js的onLoad还未执行，
                //直接设置 that.globalData.plumSession，
                //若回调函数已经创建，表示idnex的onLoad函数已经执行调用回调函数将plumSession传递
                if (that.plumSessionCallback) {
                  that.plumSessionCallback(res.data.data);
                } else {
                  that.globalData.plumSession = res.data.data;
                }
                //到此时已经登陆成功了  
              } else {
                console.log(res.data);
                console.log("登录失败");
              }
            },
            fail: function (res) {
              wx.showToast({
                title: '登录失败',
                icon: 'none'
              })
            },
            complete: function (com) {
              console.log("执行完成",com);
            }
          });
        } else { //若没有获取到登陆code
          wx.showToast({
            title: '登录失败！' + res.errMsg,
            icon: 'none',
            duration: 2000
          })
        }
      },
      fail: function (res) {
        wx.showToast({
          title: '用户code获取失败！' + res.errMsg,
          icon: 'none',
          duration: 2000
        })
      }
    });
  },
  /**
   * 初次加载判断网络情况
   */
  getNetworkType() {
    wx.getNetworkType({
      success(res) {
        const networkType = res.networkType
        if (networkType === 'none') {
          wx.showToast({
            title: '当前无网络',
            icon: 'loading',
            duration: 2000
          })
        }
      }
    });
  },
  /**
   * 监听网络状态变化
   * 可根据业务需求进行调整
   */
  onNetworkStatusChange() {
    wx.onNetworkStatusChange(function (res) {
      if (!res.isConnected) {
        wx.showToast({
          title: '网络已断开',
          icon: 'loading',
          duration: 2000,
        })
      }
    })
  },
  /**
   * 全局分享
   * 判断 邀请 还是 分享
   */
  share() {
    wx.onAppRoute(res => {
      const pages = getCurrentPages()
      const view = pages[pages.length - 1]
      wx.showShareMenu({
        withShareTicket: true
      })
      let vipType = wx.getStorageSync('userBase').vipType || 0
      let custId = wx.getStorageSync('custId')
      if (custId && vipType != 0) {
        view.onShareAppMessage = function () {
          return {
            desc: '云上漂',
            title: `${wx.getStorageSync('userBase').nickname}向您推荐南平建阳云上漂`,
            path: '/pages/index/index/index?bbId=' + wx.getStorageSync('custId'),
            imageUrl: '/static/images/shareLogo.png',
          }
        }
      } else {
        view.onShareAppMessage = function () {
          return {
            desc: '云上漂',
            title: '贵州茅台酿酒技，南平建阳云上漂，邀您共赴白酒的意境',
            path: '/pages/index/index/index',
            imageUrl: '/static/images/shareLogo.png',
          }
        }
      }

    })
  },
  /**
   * 全局分享 邀请下家注册
   */
  shareLogin() {
    wx.onAppRoute(res => {
      const pages = getCurrentPages()
      const view = pages[pages.length - 1]
      wx.showShareMenu({
        withShareTicket: true
      })
      view.onShareAppMessage = function () {
        return {
          desc: '云上漂',
          title: `${wx.getStorageSync('userBase').nickname}向您推荐南平建阳云上漂`,
          path: '/pages/index/index/index?bbId=' + wx.getStorageSync('custId'),
          imageUrl: '/static/images/shareLogo.png',
        }
      }
    })
  },
  /**
   * 全局分享 分享小程序
   */
  shareIndex() {
    wx.onAppRoute(res => {
      console.log(res);
      const pages = getCurrentPages()
      const view = pages[pages.length - 1]
      wx.showShareMenu({
        withShareTicket: true
      })
      view.onShareAppMessage = function () {
        return {
          desc: '云上漂',
          title: '贵州茅台酿酒技，南平建阳云上漂，邀您共赴白酒的意境',
          path: '/pages/index/index/index',
          imageUrl: '/static/images/shareLogo.png',
        }
      }
    })
  },
  /**
   * 是否注册
   */
  async getCustBaseByUserLoginState() {
    let resolve = await getCustBaseByUserLoginState()
    if (resolve.success) {
      wx.setStorageSync('custId', resolve.data.id || '')
      wx.setStorageSync('userBase', resolve.data)
    }
  },
  /**
   * 检测是否在有效期
   */
  checkSession() {
    /**
     * 检查登录态是否过期
     */
    wx.checkSession({
      success(res) {
        console.log('登录态未过期');
        //session_key 未过期，并且在本生命周期一直有效
      },
      fail() {
        console.log('登录态已过期');
        // session_key 已经失效，需要重新执行登录流程
      }
    })
  },
  /**
   * 配置胶囊位置信息
   */
  getMenuButtonBoundingClientRect() {
    let menuButtonObject = wx.getMenuButtonBoundingClientRect();
    wx.getSystemInfo({
      success: res => {
        let statusBarHeight = res.statusBarHeight,
          navTop = menuButtonObject.top, //胶囊按钮与顶部的距离
          navHeight = statusBarHeight + menuButtonObject.height + (menuButtonObject.top - statusBarHeight) * 2; //导航高度
        this.globalData.CustomBar = navHeight;
        this.globalData.StatusBar = navTop;
        this.globalData.windowHeight = res.windowHeight;
      },
      fail(err) {
        console.log(err);
      }
    })
  },
  /**
   * 检测当前的小程序
   * 是否是最新版本，是否需要下载、更新
   */
  checkUpdateVersion() {
    if (wx.canIUse('getUpdateManager')) {
      const updateManager = wx.getUpdateManager()
      updateManager.onCheckForUpdate(function (res) {
        if (res.hasUpdate) {
          updateManager.onUpdateReady(function () {
            wx.showModal({
              title: '更新提示',
              content: '新版本已经准备好，是否重启应用？',
              success: function (res) {
                if (res.confirm) {
                  updateManager.applyUpdate()
                }
              }
            })
          })
          updateManager.onUpdateFailed(function () {
            wx.showModal({
              title: '已经有新版本了哟~',
              content: '新版本已经上线啦~，请您删除当前小程序，重新搜索打开哟~'
            })
          })
        }
      })
    } else {
      wx.showModal({
        title: '提示',
        content: '当前微信版本过低，无法使用该功能，请升级到最新微信版本后重试。'
      })
    }
  },
})